<script setup>
import { NCard, NButton, NInput, NFlex, NForm, NFormItem } from 'naive-ui';
import logo from '../assets/logo.png';
import { ref,computed} from 'vue';
import axiosInstance from '@/utils/axios';
import router from '@/router';
import { usemsgStore } from '@/stores/msgwrapper';
import { usedialogStore } from '@/stores/dialogwrapper';
import { usecaptchaStore } from '@/stores/captcha';

// 验证码状态存储
const  captachaStore = usecaptchaStore()
const {getCaptcha} = captachaStore
const isButtonDisabled = computed(() => captachaStore.isButtonDisabled);
const countdown = computed(() => captachaStore.countdown);
// 对话框状态存储
const dialogStore = usedialogStore();
// 消息状态存储
const msgStore = usemsgStore()
const {sendMessage} = msgStore

// 短信验证码响应式数据
const loginButtonDisabled = ref(false);
const formRef = ref(null);
const formValue = ref({
  username: "",
  ver_code: "",
});
const rule = ref({
  username: {
    required: true,
    trigger: ['input'],
    message: "请输入正确的电话号码格式",
    validator: (rule, value) => /^1[3-9]\d{9}$/.test(value),
  },
  ver_code: {
    required: true,
    trigger: ['input'],
    message: "请填写验证码",
    validator: (rule, value) => value.trim() !== "" && value.length > 0,
  },
});

// 登录函数
const handleValidateClick = async (e) => {
  e.preventDefault();
  loginButtonDisabled.value = true;
  try {
    await formRef.value.validate();
    // 表单验证通过，执行登录请求
    const username = formValue.value.username;
    const ver_code = formValue.value.ver_code;
    sendMessage("loading",'正在检验登录进程', {
      duration: 1000,
      onAfterLeave: async () => {
        try {
          const res = await axiosInstance.post('/api/login', { username, ver_code });
          // 选择持久存储还是会话存储
          if (res.data.success && res.data.code === 200) {
            window.localStorage.setItem('token', res.data.message);
            dialogStore.closeDialog();
            sendMessage("success","登录成功", {
              duration: 500,
              onAfterLeave: () => {
                router.push('/home');
              }
            });
          } else {
            sendMessage("error","登录错误,请检查账号是否注册过");
          }
        } catch (error) {
          sendMessage("error","登录请求失败，请稍后再试。");
        } finally {
          formValue.value.ver_code = "";
          loginButtonDisabled.value = false;
        }
      }
    });
  } catch (errors) {
    // 处理表单验证错误
    sendMessage("error","请完整正确填写信息");
    loginButtonDisabled.value = false;
  }
};


</script>

<template>
  <n-card class="up">
    <img :src="logo" width="200px" style="margin-left: 160px; margin-top: -20px" height="150px">
  </n-card>
  <n-card class="down">
    <span style="font-weight: bold; font-size: 16px; margin-left: 225px">验证码登录</span>
    <n-flex>
      <n-form ref="formRef" :model="formValue" :rules="rule">
        <n-flex column>
          <n-form-item path="username" feedback-style="margin-top:5px;margin-left:160px;">
            <n-input v-model:value="formValue.username" placeholder="手机号" maxlength="11" style="margin-top:-30px; height: 52.6px; width:326px; font-size: 16px; line-height: 52.6px; margin-left: 100px"></n-input>
          </n-form-item>
          <n-flex gap="10px" style="margin-top:15px;">
            <n-form-item path="ver_code" feedback-style="margin-top:-10px;margin-left:200px;">
              <n-input v-model:value="formValue.ver_code" placeholder="请输入验证码" style="height: 52.6px; width:230px; font-size: 16px; line-height: 52.6px;margin-left: 100px;margin-top: -70px"></n-input>
            </n-form-item>
            <n-button
              :disabled="isButtonDisabled"
              type="primary"
              style="height: 52.6px; width:100px; background-color: cornflowerblue;margin-top: -20px;"
              @click="getCaptcha(formValue.username)"
            >
              {{ countdown > 0 ? `重新发送(${countdown})` : '获取验证码' }}
            </n-button>
          </n-flex>
        </n-flex>
        <n-button style="height: 52.6px; width:326px; margin-top:10px;margin-left: 100px" type="info" @click="handleValidateClick" :disabled="loginButtonDisabled">登录</n-button>
      </n-form>
    </n-flex>
  </n-card>
</template>

<style>
.up {
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  border: 2px solid whitesmoke;
  width: 604px;
  height: 140px;
  margin-left: -28px;
  margin-top: -30px;
  background-color: #DBEDFF;
}

.down {
  padding: 23px 40px 32px 0px;
  background-color: white;
  width: 602.9px;
  height: 408px;
  border: 2px solid whitesmoke;
  margin-left: -27px;
  border-bottom-left-radius: 25px;
  border-bottom-right-radius: 25px;
}
</style>